﻿using Networks;
using Pomelo.DotNetClient;
using SimpleJson;
using System;
using UnityEngine;
using UnityEngine.UI;

namespace game.login
{
    public class Login : MonoBehaviour
    {
        [Header("UI")]
        public InputField name_InputField;
        public InputField room_InputField;
        public Button login_btn;

        [Header("Server")]
        public string host = "192.168.10.254";
        public int port = 3014;

        private PomeloClient _pclient;

        private void Start()
        {
            login_btn.onClick.AddListener(login);
        }

        private void OnApplicationQuit()
        {
            _pclient?.disconnect();
        }

        private void login()
        {
            if (string.IsNullOrEmpty(name_InputField.text) || string.IsNullOrEmpty(room_InputField.text))
            {
                return;
            }

            Debug.Log("Connecting to gate server: " + host + ":" + port);

            _pclient = new PomeloClient();
            _pclient.initClient(host, port, () =>
            {
                //Debug.Log("PomeloClient.initClient callback.");

                _pclient.connect(data =>
                {
                    //Debug.Log("PomeloClient.connect callback.");

                    JsonObject msg = new JsonObject();
                    msg["uid"] = name_InputField.text;
                    _pclient.request(Routes.GATE_ENTRY, msg, onQuery);
                });
            });
        }

        private void onQuery(JsonObject result)
        {
            //Debug.Log("onQuery called. Acquired data from gate server.");

            if (Convert.ToInt32(result["code"]) == 200)
            {
                _pclient?.disconnect();
                _pclient = null;

                // myself
                Game.Instance.myself.username = name_InputField.text;
                Game.Instance.myself.roomid = room_InputField.text;

                string connectorHost = result["host"].ToString();
                int connectorPort = Convert.ToInt32(result["port"]);
                Debug.Log("Connecting to connector server: " + connectorHost + ":" + connectorPort);

                JsonObject user = new JsonObject();
                user.Add("username", name_InputField.text);
                user.Add("rid", room_InputField.text);
                NetworkManager.Instance.InitClient(connectorHost, connectorPort, user);
            }
            else
            {
                Debug.Log("Connection error.");
            }
        }
    }
}